package com.luckeys.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import push.Demo;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.luckeys.contants.CommonContans;
import com.luckeys.ios.vo.IosActivityVO;
import com.luckeys.ios.vo.IosCodeVO;
import com.luckeys.ios.vo.IosCommentVO;
import com.luckeys.service.ActivityService;
import com.luckeys.service.ActivityTypeService;
import com.luckeys.service.CityService;
import com.luckeys.utils.HttpsRequest;
import com.luckeys.utils.MapToXMLString;
import com.luckeys.utils.SendMSGUtil;
import com.luckeys.utils.XmlToString;
import com.luckeys.vo.ActivityTypeVO;
import com.luckeys.vo.ActivityVO;
import com.luckeys.vo.CityVO;
import com.luckeys.vo.EventsVO;
import com.luckeys.vo.ReverseReqData;
import com.luckeys.weixin.util.MD5Util;
import com.tencent.common.RandomStringGenerator;
import com.tencent.common.Signature;

@RestController
@RequestMapping(value = "/activity", method = RequestMethod.POST)
public class ActivityController {

	private static String key = "luckeys20150901luckeys20150901lq";

	// 微信分配的公众号ID（开通公众号之后可以获取到）
	private static String appID = "wxa23f475c7751896e";

	// 微信支付分配的商户号ID（开通公众号的微信支付功能之后可以获取到）
	private static String mchID = "1282966001";

	private static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALMN2ekE3obNh8RazeZaafdbdNth/Pfx40eOIcEe4A0Ox3Wk7slZo1C6g82Ymoowzv3b97kFNNohhxX98Hh0KaC4uutIq33Tm601RZtDQ6ZF3ca2WaHlZC+tk69owXv+SAAzGrhjpSRfnBy0zSQG5F2md/C2sdp5g7iF3yBbVELTAgMBAAECgYA8I57ZQSVsqYO8U7Nsd1m4FyO8u8C3lqr70aVMtA4U1K3xuZ/qSQ0thDfYyjS9zX74jPU7U6BY04IHxO8LxhhkrtNSa5dfHSGdLnAgN5i061UwnKadi3YeoU0LYbEhflswNnHrmGED8sEm+qfV+oTSROCbp14Y8u1byXWgi0A9gQJBAOjYKQx5XwNEuJ86vuDKDnKJl6Coione059EzKgzN6RxSMZo3seuYMOv7kkgfxGKgUsjm3nhhLxT5SwiRf9vHVECQQDE3Ecn2H3BZfRaV4qm8RjfKrw0iybe/Zb1AUhGD/l1plot6hGvirGzlqhCSQmZuG1LJ0ubscR9zLTM85Vz2ATjAkEAq2XDAa2uJQfHJ17k9y+FZwalmNu37zkZahoI1J+vC9tgCL1VkINqM2Ij86x6HP1po1f4sMUzIjZXch9gi2DNoQJAVhniJVNS7VuiXEEdq5aXwkP2vSR/g9h2RgKhkcM64HI5zwspYRXQUzP5s8QuJsW7R7uQHjDKOBtomJuRKnG48QJAXfnvTjHaMS0juH5IEYBQIayjfnCa00IFkcjnvbu5JIVviYL+fc499dDUbAEgb37Afmq5yzE4SArb/zgUuBLg9Q==";

	private static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzDdnpBN6GzYfEWs3mWmn3W3TbYfz38eNHjiHBHuANDsd1pO7JWaNQuoPNmJqKMM792/e5BTTaIYcV/fB4dCmguLrrSKt905utNUWbQ0OmRd3Gtlmh5WQvrZOvaMF7/kgAMxq4Y6UkX5wctM0kBuRdpnfwtrHaeYO4hd8gW1RC0wIDAQAB";

	private static String aliAppId = "2088121014981498";

	// 商户收款账号
	public static final String SELLER = "2088121014981498";
	
	// 支付宝交易状态
	public static final String TRADE_SUCCESS = "TRADE_SUCCESS";
	public static final String TRADE_FINISHED = "TRADE_FINISHED";
	
	//支付类型：微信，支付宝
	public static final String WEIXIN = "weixin";
	public static final String ALI = "ali";
	
	@Autowired
	private ActivityService activityService;

	@Autowired
	private ActivityTypeService activityTypeService;

	@Autowired
	private CityService cityService;

	@RequestMapping(value = "/queryPage", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryActivityPage(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();

		resultMap.put(CommonContans.STRUTS_DATA,
				activityService.queryActivityPage(activity));
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	/**
	 * 6.主页
	 * 
	 * @param activity
	 * @return
	 */
	@RequestMapping(value = "/queryIosPage", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryIosPage(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		if (StringUtils.isNotBlank(activity.getCityName())) {
			activity.setCityName("深圳");
		}
		// 默认活动开始页面
		activity.setActivityStatus("2");
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.queryIosPage(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/querySharePage", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap querySharePage(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.querySharePage(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}
	
	@RequestMapping(value = "/queryOrderList", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryOrderList(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.queryOrderList(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryCommentPage", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryCommentPage(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.queryCommentPage(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryCollectPage", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryCollectPage(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.queryCollectPage(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryPraisePage", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryPraisePage(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.queryPraisePage(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryCodeList", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryCodeList(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.queryNotUserCode(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	/**
	 * 用户选择支付方式的时候锁定投注码
	 * 
	 * @param activity
	 * @return
	 */
	@RequestMapping(value = "/betCode", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap betCode(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		activity.setIsWin("2");
		activity.setOldIsWin("0");
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("listCode", activityService.betCode(activity));
		resultMap.put(CommonContans.STRUTS_BODY, result);

		activity.setIsWin("0");
		activity.setOldIsWin("2");
		activity.setUserUuid(null);
		updateCode(activity, activityService);
		// List<IosCodeVO> listCode =
		// activityService.queryNotUserCode(activity);
		// if (CollectionUtils.isEmpty(listCode) || listCode.size() == 0) {
		// // 修改活动的状态为结束，并且设置众筹成功
		// activity.setChipsStatus("1");
		// activity.setActivityStatus("3");
		// activity.setEndDate(new Date());
		// endActivity(activity, activityService);
		//
		// // 设置中奖人
		// List<IosCodeVO> listCode1 = activityService.queryListCode(activity);
		// Random random = new Random();
		// IosCodeVO winCode = listCode1.get(random.nextInt(listCode1.size()));
		// activityService.updateCode(winCode);
		// try {
		// Demo demo = new Demo("55eafa6767e58eef8300f77a",
		// "acfofwujhwgfzck9enfuf5jza0ynfwjv");
		// Set<String> iosToken = new HashSet<String>();
		// for (IosCodeVO code : listCode1) {
		// if (StringUtils.isNotBlank(code.getIosDeviceToken())) {
		// iosToken.add(code.getIosDeviceToken());
		// code.setTitle("你参加的活动已众筹成功，将于5分钟之后开奖。");
		// code.setActivityUuid(activity.getActivityUuid());
		// demo.sendIOSUnicast(code);
		// }
		// }
		// winCode.setTitle("恭喜活动中奖");
		// winCode.setActivityUuid(activity.getActivityUuid());
		// if (StringUtils.isNotBlank(winCode.getIosDeviceToken())) {
		// pushWin(winCode, demo);
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	public static void updateCode(final ActivityVO activity,
			final ActivityService activityService) {
		final StopWatch watch = new StopWatch();
		watch.start();
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				watch.stop();
				System.out.println("-------任务执行--------");
				try {
					activityService.betCode(activity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 120 * 1000);
	}

	public static void endActivity(final ActivityVO activity,
			final ActivityService activityService) {
		final StopWatch watch = new StopWatch();
		watch.start();
		Timer timer = new Timer();
		/* void java.util.Timer.schedule(TimerTask task, long delay) */
		timer.schedule(new TimerTask() {
			public void run() {
				watch.stop();
				System.out.println("-------任务执行--------");
				try {
					activityService.updateActivity(activity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 300 * 1000);
	}

	public static void pushWin(final IosCodeVO winCode, final Demo demo) {
		final StopWatch watch = new StopWatch();
		watch.start();
		Timer timer = new Timer();
		/* void java.util.Timer.schedule(TimerTask task, long delay) */
		timer.schedule(new TimerTask() {
			public void run() {
				watch.stop();
				System.out.println("-------任务执行--------");
				try {
					demo.sendIOSUnicast(winCode);
					SendMSGUtil.sendMSG(null, null, winCode.getUserPhone(),
							"恭喜你参加的活动中奖,请打开乐其APP,查看详情.");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 300 * 1000);// 5分钟后推送中奖信息
	}

	@RequestMapping(value = "/queryList", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryListActivity(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();

		resultMap.put(CommonContans.STRUTS_DATA,
				activityService.queryActivityList(activity));
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryActivityById", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryActivityById(String activityUuid) {
		ModelMap resultMap = new ModelMap();
		ActivityVO Activity = activityService.queryActivityById(activityUuid);
		resultMap.put(CommonContans.STRUTS_DATA, Activity);
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	/**
	 * 7.活动详情
	 * 
	 * @param activityVO
	 * @return
	 */
	@RequestMapping(value = "/queryIosActivityById", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryIosActivityById(@RequestBody ActivityVO activityVO) {
		ModelMap resultMap = new ModelMap();
		IosActivityVO activity = activityService
				.queryIosActivityById(activityVO);
		resultMap.put(CommonContans.STRUTS_BODY, activity);
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryWinByUserId", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryWinByUserId(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.queryWinByUserId(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryBetByUserId", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryBetByUserId(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.queryBetByUserId(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryActivityImageById", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryActivityImageById(String activityUuid) {
		ModelMap resultMap = new ModelMap();
		ActivityVO activity = activityService.queryActivityById(activityUuid);
		resultMap.put(CommonContans.STRUTS_DATA, activity);
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/updateActivity", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap updateActivity(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_DATA,
				activityService.updateActivity(activity));
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/addActivity", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public ModelAndView addActivity(ActivityVO activity,
			@RequestParam MultipartFile[] myfiles, HttpServletRequest request)
			throws Exception {
		ModelMap resultMap = new ModelMap();

		DecimalFormat df;

		// 设置当前抽奖码
		List<String> listCode = new ArrayList<String>();
		int m, d;
		String year;
		Calendar cal = Calendar.getInstance();
		year = new SimpleDateFormat("yy", Locale.CHINESE).format(cal.getTime());
		m = cal.get(Calendar.MONTH) + 1;
		d = cal.get(Calendar.DATE);
		ActivityTypeVO activityType = activityTypeService
				.queryActivityTypeById(activity.getActivityTypeUuid());
		String day = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
		EventsVO events = new EventsVO();
		events.setEventsDay(day);
		events.setActivitytypeUuid(activityType.getActivityTypeUuid());
		events = activityService.queryEvents(events);
		if (null == events) {
			events = new EventsVO();
			events.setEventsUuid(UUID.randomUUID().toString());
			events.setEventsDay(day);
			events.setActivitytypeUuid(activityType.getActivityTypeUuid());
			if ("1".equals(activityType.getActivityTypeUuid())) {
				events.setEventsNumber("000");
			} else {
				events.setEventsNumber("00");
			}
			try {
				activityService.addEvents(events);
			} catch (DuplicateKeyException e) {
				events = activityService.queryEvents(events);
			}
		}
		if (events != null) {
			// 电影场次三位数，其他两位数
			if ("1".equals(activityType.getActivityTypeUuid())) {
				df = new DecimalFormat("000");
			} else {
				df = new DecimalFormat("00");
			}
			Integer eventsNumber = Integer.valueOf(events.getEventsNumber());
			events.setOldEventsNumber(df.format(eventsNumber));
			events.setEventsNumber(df.format(eventsNumber + 1));
			int result = activityService.updateEvents(events);
			while (result == 0) {
				eventsNumber++;
				events.setOldEventsNumber(df.format(eventsNumber));
				events.setEventsNumber(df.format(eventsNumber + 1));
				result = activityService.updateEvents(events);
			}
		}
		CityVO city = cityService.queryCityById(activity.getCityUuid());
		activity.setActivityUuid(UUID.randomUUID().toString());
		activity.setUserUuid("2");
		Integer bets = (int) (activity.getTotalPrice() / activity
				.getUnitPrice());
		activity.setBets(bets);
		for (int i = 1; i <= bets; i++) {
			if ("1".equals(activityType.getActivityTypeUuid())) {
				df = new DecimalFormat("00");
			} else {
				df = new DecimalFormat("000");
			}
			String a = df.format(i);
			listCode.add(city.getCityCode()
					+ activityType.getActivityTypeCode() + year + m + d
					+ events.getEventsNumber() + a);
		}
		// 抽奖码完成
		List<String> listImageUrl = new ArrayList<String>();
		for (MultipartFile myfile : myfiles) {
			if (myfile.isEmpty()) {
			} else {
				String realPath = request.getSession().getServletContext()
						.getRealPath("/image/activity");
				String fileName = System.currentTimeMillis()
						+ "."
						+ StringUtils.lowerCase(myfile.getOriginalFilename()
								.split("\\.")[1]);
				String file = "/image/activity/" + fileName;
				listImageUrl.add(file);
				FileUtils.copyInputStreamToFile(myfile.getInputStream(),
						new File(realPath, fileName));
			}
		}
		activity.setListImage(listImageUrl);
		activity.setListCode(listCode);
		// 根据开始时间和活动周期(单位小时)设置结束时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = sdf.parse(activity.getStartDate());
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.HOUR, Integer.parseInt(activity.getActivityDay()));
		activity.setEndDate(c.getTime());
		// end....
		// 活动未开始
		Date nowDate = new Date();
		if (nowDate.before(date)) {
			activity.setActivityStatus("1");
			activity.setStartDate1(date);
			startActivity(activity, activityService);
		} else {
			activity.setActivityStatus("2");
		}
		activity.setCreateDate(nowDate);
		activityService.addActivity(activity);
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		// return resultMap;
		return new ModelAndView(
				"redirect:/resources/admin/view/luckeys/activity/listActivity.jsp");
	}

	public static void startActivity(final ActivityVO activity,
			final ActivityService activityService) {
		final StopWatch watch = new StopWatch();
		watch.start();
		Timer timer = new Timer();
		/* void java.util.Timer.schedule(TimerTask task, long delay) */
		timer.schedule(new TimerTask() {
			public void run() {
				watch.stop();
				System.out.println("-------任务执行--------");
				ActivityVO activityVO = new ActivityVO();
				activityVO.setActivityUuid(activity.getActivityUuid());
				activityVO.setActivityStatus("2");
				activityService.updateActivity(activityVO);
			}
		}, activity.getStartDate1());// delay=2000毫秒 后执行该任务
	}

	@RequestMapping(value = "/addActivityImage", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public ModelAndView addActivityImage(ActivityVO activity,
			@RequestParam MultipartFile[] myfiles, HttpServletRequest request)
			throws Exception {
		ModelMap resultMap = new ModelMap();
		// 如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解
		// 如果想上传多个文件，那么这里就要用MultipartFile[]类型来接收文件，并且还要指定@RequestParam注解
		// 并且上传多个文件时，前台表单中的所有<input
		// type="file"/>的name都应该是myfiles，否则参数里的myfiles无法获取到所有上传的文件
		List<String> listImageUrl = new ArrayList<String>();
		for (MultipartFile myfile : myfiles) {
			if (myfile.isEmpty()) {
				System.out.println("文件未上传");
			} else {
				System.out.println("文件长度: " + myfile.getSize());
				System.out.println("文件类型: " + myfile.getContentType());
				System.out.println("文件名称: " + myfile.getName());
				System.out.println("文件原名: " + myfile.getOriginalFilename());
				System.out.println("========================================");
				// 如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
				String realPath = request.getSession().getServletContext()
						.getRealPath("/image/Activity");
				String fileName = System.currentTimeMillis()
						+ "."
						+ StringUtils.lowerCase(myfile.getOriginalFilename()
								.split("\\.")[1]);
				String file = "/image/Activity/" + fileName;
				listImageUrl.add(file);
				// 这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
				FileUtils.copyInputStreamToFile(myfile.getInputStream(),
						new File(realPath, fileName));
			}
		}
		activity.setListImage(listImageUrl);
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		// return resultMap;
		return new ModelAndView(
				"redirect:/resources/admin/view/luckeys/activity/listActivityImage.jsp?activityUuid="
						+ activity.getActivityUuid());
	}

	@RequestMapping(value = "/deleteActivity", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap deleteActivity(String activityUuid) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_DATA,
				activityService.deleteActivity(activityUuid));
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/operCollection", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap operCollection(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		activityService.operCollection(activity);
		IosActivityVO activityVO = new IosActivityVO();
		activityVO.setActivityUuid(activity.getActivityUuid());
		resultMap.put(CommonContans.STRUTS_BODY, activityVO);
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/addComment", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap addComment(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		activity.setCommentUuid(UUID.randomUUID().toString());
		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.addComment(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/addUse", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap addUse(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		activity.setUseUuid(UUID.randomUUID().toString());
		activityService.addUse(activity);
		IosCommentVO comment = new IosCommentVO();
		comment.setCommentUuid(activity.getCommentUuid());
		resultMap.put(CommonContans.STRUTS_BODY, comment);
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/praiseWin", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap praiseWin(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		activity.setPraiseUuid(UUID.randomUUID().toString());
		activityService.praiseWin(activity);
		resultMap.put(CommonContans.STRUTS_BODY, activity);
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/paySuccess", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap paySuccess(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();

		resultMap.put(CommonContans.STRUTS_BODY,
				activityService.paySuccess(activity));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);

		List<IosCodeVO> listCode = activityService.queryNotUserCode(activity);
		if (CollectionUtils.isEmpty(listCode) || listCode.size() == 0) {
			// 修改活动的状态为结束，并且设置众筹成功
			activity.setChipsStatus("1");
			activity.setActivityStatus("3");
			activity.setEndDate(new Date());
			endActivity(activity, activityService);

			// 设置中奖人
			List<IosCodeVO> listCode1 = activityService.queryListCode(activity);
			Random random = new Random();
			IosCodeVO winCode = listCode1.get(random.nextInt(listCode1.size()));
			activityService.updateCode(winCode);
			try {
				Demo demo = new Demo("55eafa6767e58eef8300f77a",
						"acfofwujhwgfzck9enfuf5jza0ynfwjv");
				Set<String> iosToken = new HashSet<String>();
				for (IosCodeVO code : listCode1) {
					if (StringUtils.isNotBlank(code.getIosDeviceToken())) {
						iosToken.add(code.getIosDeviceToken());
					}
				}
				for (String code : iosToken) {
					IosCodeVO codeVO = new IosCodeVO();
					codeVO.setTitle("你参加的活动已众筹成功，将于5分钟之后开奖。");
					codeVO.setActivityUuid(activity.getActivityUuid());
					codeVO.setIosDeviceToken(code);
					demo.sendIOSUnicast(codeVO);
				}
				winCode.setTitle("恭喜活动中奖");
				winCode.setActivityUuid(activity.getActivityUuid());
				if (StringUtils.isNotBlank(winCode.getIosDeviceToken())) {
					pushWin(winCode, demo);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultMap;
	}

	@RequestMapping(value = "/alipay", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap alipay(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		Map<String, String> mapResult = new HashMap<String, String>();
		String outTradeNo = String.valueOf(System.currentTimeMillis());
		try {
			// 订单
			String orderInfo = getOrderInfo(activity.getActivityName(),
					activity.getDescription(), (int)(activity
							.getUnitPrice() * activity.getBets()), outTradeNo);

			// 对订单做RSA 签名
			String sign = AlipaySignature.rsaSign(orderInfo, privateKey,
					"utf-8");
			try {
				// 仅需对sign 做URL编码
				sign = URLEncoder.encode(sign, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			// 完整的符合支付宝参数规范的订单信息
			final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
					+ getSignType();

			// String test = AlipaySignature.rsaSign(mapResult, privateKey,
			// "utf-8");
			mapResult.put("payInfo", payInfo);
			resultMap.put(CommonContans.STRUTS_BODY, mapResult);
			resultMap.put(CommonContans.STRUTS_CODE,
					CommonContans.STRUTS_SUCCESS);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@RequestMapping(value = "/pay", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap pay(@RequestBody ActivityVO activity) {
		ModelMap resultMap = new ModelMap();
		Map<String, Object> mapResult = new HashMap<String, Object>();
		// 判断号码是否还是被锁定
		activity.setIsWin("3");
		activity.setOldIsWin("2");
		List<String> listCode = activityService.betCode(activity);
		if (listCode.size() > 0) {
			activity.setIsWin("3");
			activity.setOldIsWin("3");
			listCode = activityService.betCode(activity);
			if(listCode.size() > 0)
			{
				mapResult.put("isTimeOut", "1");
			}
		} 
		if(!"1".equals(mapResult.get("isTimeOut"))){
			// 0:未超时
			mapResult.put("isTimeOut", "0");
			
			String outTradeNo = String.valueOf(System.currentTimeMillis());
			String prepayId = null;
			if(WEIXIN.equals(activity.getPayType()))
			{
				ReverseReqData ReverseReqData = new ReverseReqData();
				ReverseReqData.setAppid(appID);
				ReverseReqData.setAttach(activity.getActivityName());
				ReverseReqData.setBody(activity.getDescription());
				ReverseReqData.setMch_id(mchID);
				ReverseReqData.setNonce_str(RandomStringGenerator
						.getRandomStringByLength(32));
				ReverseReqData
						.setNotify_url("http://120.55.241.27:8080/luckeys/activity/notify");
				ReverseReqData.setOut_trade_no(outTradeNo);
				ReverseReqData.setSpbill_create_ip("120.55.241.27");
				ReverseReqData.setTotal_fee(String.valueOf((int) (activity
						.getUnitPrice() * activity.getBets() * 100)));
				ReverseReqData.setTrade_type("APP");
				ReverseReqData.setSign(Signature.getSign(ReverseReqData.toMap()));
				Map<Object, Object> mapNew = new HashMap<Object, Object>();
				mapNew.putAll(ReverseReqData.toMap());
				String body = MapToXMLString.converter(mapNew);

				String result = "";
				try {
					System.out.println("body:" + body);
					// 下单接口
					result = new HttpsRequest().sendPost(
							"https://api.mch.weixin.qq.com/pay/unifiedorder", body);
					mapResult = new XmlToString().xmlTOMap(result);
					if("SUCCESS".equals(mapResult.get("return_code"))&&"SUCCESS".equals(mapResult.get("result_code")))
					{
						Map<String, Object> map = new HashMap<String, Object>();
						String noncestr = RandomStringGenerator
								.getRandomStringByLength(32);
						String timestamp = String
								.valueOf(System.currentTimeMillis() / 1000);
						map.put("appid", appID);
						map.put("noncestr", noncestr);
						map.put("package", activity.getWxPackage());
						map.put("partnerid", mchID);
						map.put("prepayid", mapResult.get("prepay_id"));
						map.put("timestamp", timestamp);
						mapResult.put("paySign", Signature.getSign(map));
						mapResult.put("payNoncestr", noncestr);
						mapResult.put("payTimestamp", timestamp);
						mapResult.put("timeShamp", System.currentTimeMillis());
	
						prepayId = (String) mapResult.get("prepay_id");
					}else
					{
						resultMap.put(CommonContans.STRUTS_MESSAGE, "return_code or result_code is not success.");
						resultMap.put(CommonContans.STRUTS_CODE,
								CommonContans.STRUTS_ERROR);
						return resultMap;
					}
				} catch (HttpException e) {
					resultMap.put(CommonContans.STRUTS_MESSAGE, e);
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_ERROR);
					e.printStackTrace();
					return resultMap;
				} catch (IOException e) {
					resultMap.put(CommonContans.STRUTS_MESSAGE, e);
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_ERROR);
					e.printStackTrace();
					return resultMap;
				} catch (Exception e) {
					resultMap.put(CommonContans.STRUTS_MESSAGE, e);
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_ERROR);
					e.printStackTrace();
					return resultMap;
				}
			}else if (ALI.equals(activity.getPayType()))
			{
				try {
					// 订单
					String orderInfo = getOrderInfo(activity.getActivityName(),
							activity.getDescription(), (int)(activity
									.getUnitPrice() * activity.getBets()), outTradeNo);

					// 对订单做RSA 签名
					String sign = AlipaySignature.rsaSign(orderInfo, privateKey,
							"utf-8");
					try {
						// 仅需对sign 做URL编码
						sign = URLEncoder.encode(sign, "utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}

					// 完整的符合支付宝参数规范的订单信息
					final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
							+ getSignType();

					// String test = AlipaySignature.rsaSign(mapResult, privateKey,
					// "utf-8");
					mapResult.put("payInfo", payInfo);
					resultMap.put(CommonContans.STRUTS_BODY, mapResult);
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_SUCCESS);
				} catch (AlipayApiException e) {
					resultMap.put(CommonContans.STRUTS_MESSAGE, e);
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_ERROR);
					e.printStackTrace();
					return resultMap;
				}
			}else
			{
				resultMap.put(CommonContans.STRUTS_MESSAGE, "payType is null...");
				resultMap.put(CommonContans.STRUTS_CODE,
						CommonContans.STRUTS_ERROR);
				return resultMap;
			}
			activity.setOutTradeNo(outTradeNo);
			activity.setPrepayId(prepayId);
			activity.setIsWin(null);
			activity.setOldIsWin(null);
			activityService.betCode(activity);
			
			activity.setIsWin("0");
			activity.setOldIsWin("3");
			activity.setUserUuid(null);
			activity.setPrepayId(null);
			closeOrder(activity, activityService);
			
		}

		resultMap.put(CommonContans.STRUTS_BODY, mapResult);
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	public static void closeOrder(final ActivityVO activity,
			final ActivityService activityService) {
		final StopWatch watch = new StopWatch();
		watch.start();
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				watch.stop();
				System.out.println("closeOrder start..");
				try {

					ReverseReqData ReverseReqData = new ReverseReqData();
					ReverseReqData.setAppid(appID);
					ReverseReqData.setMch_id(mchID);
					ReverseReqData.setNonce_str(RandomStringGenerator
							.getRandomStringByLength(32));
					ReverseReqData.setOut_trade_no(activity.getOutTradeNo());
					ReverseReqData.setSign(Signature.getSign(ReverseReqData
							.toMap()));
					Map<Object, Object> mapNew = new HashMap<Object, Object>();
					mapNew.putAll(ReverseReqData.toMap());
					String body = MapToXMLString.converter(mapNew);

					String result = "";
					Map<String, Object> mapResult = new HashMap<String, Object>();
					result = new HttpsRequest().sendPost(
							"https://api.mch.weixin.qq.com/pay/closeorder",
							body);
					mapResult = new XmlToString().xmlTOMap(result);
					System.out.println(mapResult.get("return_code"));
					activity.setOutTradeNo(null);
					activityService.betCode(activity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 120 * 1000);
	}

	// @RequestMapping(value = "/aliPay", consumes = "application/json",
	// produces = "application/json")
	// @ResponseBody
	// public ModelMap aliPay(@RequestBody ActivityVO activity) {
	// ModelMap resultMap = new ModelMap();
	// AlipayClient alipayClient = new DefaultAlipayClient(
	// "https://openapi.alipaydev.com/gateway.do", aliAppId,
	// privateKey, "json", "GBK", publicKey);
	// AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
	// request.setBizContent("");
	// try {
	// AlipayTradePrecreateResponse response = alipayClient
	// .execute(request);
	// } catch (AlipayApiException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// resultMap.put(CommonContans.STRUTS_BODY, "");
	// resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
	// return resultMap;
	// }

	public String getXmlBody(Map<Object, Object> map) {
		StringBuffer sb = new StringBuffer();
		Set es = map.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = String.valueOf(entry.getValue());
			if (!"appkey".equals(k)) {
				sb.append("<" + k + ">" + v + "<" + k + ">" + "\r\n");
			}
		}
		return sb.toString();
	}

	/**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 */
	protected String createSign(Map<String, Object> map) {
		StringBuffer sb = new StringBuffer();
		Set es = map.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=luckeys20150901luckeys20150901lq");

		String sign = MD5Util.MD5Encode(sb.toString(), "utf8").toUpperCase();

		return sign;

	}

	@RequestMapping(value = "/shareActivity", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public ModelMap shareActivity(ActivityVO activity,
			@RequestParam MultipartFile[] myfiles, HttpServletRequest request)
			throws Exception {
		ModelMap resultMap = new ModelMap();
		List<String> listImage = new ArrayList<String>();
		try {
			String file = "";
			for (MultipartFile myfile : myfiles) {
				if (myfile.isEmpty()) {

				} else {
					String realPath = request.getSession().getServletContext()
							.getRealPath("/image/share");
					String fileName = System.currentTimeMillis()
							+ "."
							+ StringUtils.lowerCase(myfile
									.getOriginalFilename().split("\\.")[1]);
					file = "/image/share/" + fileName;
					listImage.add(file);
					FileUtils.copyInputStreamToFile(myfile.getInputStream(),
							new File(realPath, fileName));
				}
			}
			activity.setListImage(listImage);
			activityService.shareActivity(activity);
			// resultMap.put(CommonContans.STRUTS_BODY,user);
			resultMap.put(CommonContans.STRUTS_CODE,
					CommonContans.STRUTS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put(CommonContans.STRUTS_MESSAGE, "分享失败");
			resultMap
					.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_ERROR);
		}
		return resultMap;
	}

	@RequestMapping(value = "/notify", method = RequestMethod.POST)
	@ResponseBody
	public void notify(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out
				.println("---------------wexin start----------------------------");
		ModelMap resultMap = new ModelMap();
		String inputLine;
		String notityXml = "";
		String resXml = "";

		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();

			Map<String, Object> mapResult = new XmlToString()
					.xmlTOMap(notityXml);

			ActivityVO activity = new ActivityVO();
			activity.setOutTradeNo((String) mapResult.get("out_trade_no"));
			System.out.println("success:"
					+ activityService.paySuccess(activity));

			List<IosCodeVO> listCode = activityService
					.queryCodeByOutTradeNo(activity);
			if (CollectionUtils.isEmpty(listCode) || listCode.size() == 0) {
				// 修改活动的状态为结束，并且设置众筹成功
				activity.setChipsStatus("1");
				activity.setEndDate(new Date());
				
				activityService.updateActivity(activity);
				activity.setActivityStatus("3");
				endActivity(activity, activityService);

				// 设置中奖人
				List<IosCodeVO> listCode1 = activityService
						.queryListCode(activity);
				Random random = new Random();
				IosCodeVO winCode = listCode1.get(random.nextInt(listCode1
						.size()));
				activityService.updateCode(winCode);
				try {
					Demo demo = new Demo("55eafa6767e58eef8300f77a",
							"acfofwujhwgfzck9enfuf5jza0ynfwjv");
					Set<String> iosToken = new HashSet<String>();
					for (IosCodeVO code : listCode1) {
						if (StringUtils.isNotBlank(code.getIosDeviceToken())) {
							iosToken.add(code.getIosDeviceToken());
						}
					}
					for (String code : iosToken) {
						IosCodeVO codeVO = new IosCodeVO();
						codeVO.setTitle("你参加的活动已众筹成功，将于5分钟之后开奖。");
						codeVO.setActivityUuid(activity.getActivityUuid());
						codeVO.setIosDeviceToken(code);
						demo.sendIOSUnicast(codeVO);
					}
					winCode.setTitle("恭喜活动中奖");
					winCode.setActivityUuid(activity.getActivityUuid());
					if (StringUtils.isNotBlank(winCode.getIosDeviceToken())) {
						pushWin(winCode, demo);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			System.out.println(notityXml);
			StringBuffer returnXML = new StringBuffer();
			returnXML.append("<xml>");
			returnXML.append("<return_code><![CDATA[SUCCESS]]></return_code>");
			returnXML.append("<return_msg><![CDATA[OK]]></return_msg>");
			returnXML.append("</xml>");
			System.out.println(returnXML.toString());
			response.getWriter().write(returnXML.toString());

			System.out
					.println("---------------wexin end----------------------------");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// return resultMap;

	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, int price,
			String outTradeNo) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + aliAppId + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + outTradeNo + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
//		orderInfo += "&body=" + "\"" + body + "\"";
		orderInfo += "&body=" + "\"" + "11111" + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\""
				+ "http://120.55.241.27:8080/luckeys/activity/callback" + "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
//		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	@RequestMapping(value = "/callback", method = RequestMethod.POST)
	public String callback(HttpServletRequest request,
			@RequestParam("out_trade_no") String out_trade_no,
			@RequestParam("trade_status") String trade_status,
			@RequestParam("total_fee") Double total_fee) {
		System.out.println("-----------alipay start-------------------");
		try {
			// 签名回调校验成功，处理订单逻辑
			if (TRADE_SUCCESS.equals(trade_status) || TRADE_FINISHED.equals(trade_status)) {
				ActivityVO activity = new ActivityVO();
				activity.setOutTradeNo(out_trade_no);
				System.out.println("success:"
						+ activityService.paySuccess(activity));

				List<IosCodeVO> listCode = activityService
						.queryCodeByOutTradeNo(activity);
				if (CollectionUtils.isEmpty(listCode) || listCode.size() == 0) {
					// 修改活动的状态为结束，并且设置众筹成功
					activity.setChipsStatus("1");
					activity.setEndDate(new Date());

					activityService.updateActivity(activity);
					activity.setActivityStatus("3");
					
					endActivity(activity, activityService);

					// 设置中奖人
					List<IosCodeVO> listCode1 = activityService
							.queryListCode(activity);
					Random random = new Random();
					IosCodeVO winCode = listCode1.get(random.nextInt(listCode1
							.size()));
					activityService.updateCode(winCode);
					try {
						Demo demo = new Demo("55eafa6767e58eef8300f77a",
								"acfofwujhwgfzck9enfuf5jza0ynfwjv");
						Set<String> iosToken = new HashSet<String>();
						for (IosCodeVO code : listCode1) {
							if (StringUtils.isNotBlank(code.getIosDeviceToken())) {
								iosToken.add(code.getIosDeviceToken());
							}
						}
						for (String code : iosToken) {
							IosCodeVO codeVO = new IosCodeVO();
							codeVO.setTitle("你参加的活动已众筹成功，将于5分钟之后开奖。");
							codeVO.setActivityUuid(activity.getActivityUuid());
							codeVO.setIosDeviceToken(code);
							demo.sendIOSUnicast(codeVO);
						}
						winCode.setTitle("恭喜活动中奖");
						winCode.setActivityUuid(activity.getActivityUuid());
						if (StringUtils.isNotBlank(winCode.getIosDeviceToken())) {
							pushWin(winCode, demo);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			System.out.println("支付宝回调处理失败 - orderNo:" + out_trade_no+","+ e);
		}
		System.out.println("-----------alipay end-------------------");
		return "success";//返回正常支付宝那边
	}
}
